import request from '@/config/axios'
import _ from 'lodash-es'

const baseURL = '/system/chuang-kit'

// const appId = '1cf71fc825044b6ea6858ce9bbd8b663'
// const appSecret = '12AC40EE69C9866487DAD7085E75DCAE'
// const packageId = '162'
// const settingCode = 'W4WR'

export type TokenRespVO = {
  accessToken: string
  tokenExpireTime: number
  refreshToken: string
  refreshTokenExpireTime: number
}

export type GetUserDesignsRespVO = {
  designId: String
  designTitle: String
  kindId: number
  kindName: String
  designWidth: String
  designHeight: String
  createTime: number
  updateTime: number
  thumbUrl: String
  thumbnailsState: number
  templateIds: number[]
  mobileShow: Boolean
}

export type GetUserDesignsReqVO = {
  userFlag: string
  token: string
  kindId: number
  timeOrder: number
  pageNo: number
  pageSize: number
  terminal: number
  designName: string
}

export type DeleteDesignReqVO = {
  userFlag: string
  token: string
  designIds: string
  terminal: number
}

export type CopyDesignReqVO = {
  userFlag: string
  token: string
  designId: string
  terminal: number
}

export type CopyDesignRespVO = {
  designId: string
}

export type UpdateTitleReqVO = {
  userFlag: string
  token: string
  designId: string
  terminal: number
  title: string
}

export type TemplateCollectionReqVO = {
  userFlag: string
  token: string
  templateId: string
}

export type TemplateCancelCollectionReqVO = {
  userFlag: string
  token: string
  templateId: string
}

export type TemplateCollectionListReqVO = {
  userFlag: string
  token: string
  pageNo: number
  pageSize: number
  kindId?: number
}

export type TemplateCollectionListRespVO = {
  templateId: number
  templateTitle: string
  kindId: number
  kindName: string
  createTime: string
  imageUrl: string
  width: string
  height: string
  price: number
}

export type TemplateForApiUserReqVO = {
  apiToken: string
  kindIds: number
  kindIdType: string
  industryTagIds: string
  colorTagIds: string
  styleTagIds: string
  useTagIds: string
  isTagCombinedQuery: number
  format: number
  sortType: number
  priceType: number
  keyword: string
  accurateSearch: number
  pageNo: number
  pageSize: number
  thumbnailsType: number
  onlyApi: number
  terminalType: number
  userFlag: string
  templateTypes: number
}

export type TemplateForApiUserRespVO = {
  hasNext: boolean
  totalCount: number
  resultCount: number
  queryDesignTemplateBeanList: QueryDesignTemplateBeanListDTO[]
  industry: Record<string, string>
}

export type QueryDesignTemplateBeanListDTO = {
  designKindId: number
  designTemplateId: number
  templateTitle: string
  designTemplateImageUrl: string
  customThumbnailsUrl: string
  cutDownTemplateImageUrl: string
  price: number
  priceType: number
  keywords: string
  width: string
  height: string
  collect: boolean
  industryTagRecordSoList: object
  usageTagRecordSoList: object
  styleTagRecordSoList: object
  colorTagRecordSoList: object
}

export type CenterSignReqVO = {
  appId: string
  settingCode: string
  timestamp: number
}

// 获取模板中心的sign值
export const getTemplateCenterSign = (data: CenterSignReqVO) =>
  request.post<string>({ url: `${baseURL}/get-template-center-sign`, data })

// 获取模板编辑器的sign
export const getTemplateEditorSign = (data: Record<string, string | number>) =>
  request.post<string>({ url: `${baseURL}/get-template-editor-sign`, data })

// 获取ApiToken请求中的sign
export const getApiTokenSign = () => request.get<string>({ url: `${baseURL}/get-token-sign` })

// 获取packageId
export const requestPackageId = () => request.post<string>({ url: `${baseURL}/request-package-id` })

// 获取token
export const getApiToken = () => request.get<TokenRespVO>({ url: `${baseURL}/get-token` })

// 刷新 token
export const refreshApiToken = (refreshToken: string) =>
  request.get<TokenRespVO>({ url: `${baseURL}/refresh-token`, params: { refreshToken } })

export const getLocalApiToken = async (): Promise<string> => {
  const apiTokenStr = localStorage.getItem('cktApiToken')
  let apiTokenObj = JSON.parse(apiTokenStr || '{}') as any
  // 本地有token记录
  if (apiTokenObj?.accessToken) {
    // 判断是否过期
    const { refreshToken, refreshTokenExpireTime, tokenExpireTime } = apiTokenObj as TokenRespVO
    // 已过期
    if (tokenExpireTime < Date.now()) {
      // 但可刷新
      if (refreshTokenExpireTime > Date.now()) {
        apiTokenObj = await refreshApiToken(refreshToken)
        localStorage.setItem('cktApiToken', JSON.stringify(apiTokenObj))
        return apiTokenObj.accessToken
      } else {
        // 无法刷新
        apiTokenObj = await getApiToken()
        localStorage.setItem('cktApiToken', JSON.stringify(apiTokenObj))
        return apiTokenObj.accessToken
      }
    } else {
      // 未过期
      return apiTokenObj.accessToken
    }
  } else {
    // 本地无token记录
    apiTokenObj = await getApiToken()
    localStorage.setItem('cktApiToken', JSON.stringify(apiTokenObj))
    return apiTokenObj.accessToken
  }
}

// 查询我的设计
export const listUserDesigns = async (data: Omit<GetUserDesignsReqVO, 'token'>) =>
  request.post<PageResult<GetUserDesignsRespVO>>({
    url: `${baseURL}/list-user-designs`,
    data: { ...data, token: await getLocalApiToken() }
  })

// 删除,批量删除用户设计
export const deleteDesign = async (data: Omit<DeleteDesignReqVO, 'token'>) =>
  request.post<Boolean>({
    url: `${baseURL}/delete-design`,
    data: { ...data, token: await getLocalApiToken() }
  })

// 复制用户设计
export const copyDesign = async (data: Omit<CopyDesignReqVO, 'token'>) =>
  request.post<CopyDesignRespVO>({
    url: `${baseURL}/copy-design`,
    data: { ...data, token: await getLocalApiToken() }
  })

// 修改设计名称
export const updateTitle = async (data: Omit<UpdateTitleReqVO, 'token'>) =>
  request.post<Boolean>({
    url: `${baseURL}/update-title`,
    data: { ...data, token: await getLocalApiToken() }
  })

// 模板收藏接口
export const templateCollection = async (data: Omit<TemplateCollectionReqVO, 'token'>) =>
  request.post<Boolean>({
    url: `${baseURL}/template-collection`,
    data: { ...data, token: await getLocalApiToken() }
  })

// 模板取消收藏接口
export const templateCancelCollection = async (
  data: Omit<TemplateCancelCollectionReqVO, 'token'>
) =>
  request.post<Boolean>({
    url: `${baseURL}/template-cancel-collection`,
    data: { ...data, token: await getLocalApiToken() }
  })

// 查询收藏的模板
export const getTemplateCollection = async (data: Omit<TemplateCollectionListReqVO, 'token'>) =>
  request.post<TemplateCollectionListRespVO[]>({
    url: `${baseURL}/list-template-collection`,
    data: { ...data, token: await getLocalApiToken() }
  })

// 获取创客贴官方模板
export const queryTemplateForApiUser = async (data: Omit<TemplateForApiUserReqVO, 'apiToken'>) =>
  request.post<TemplateForApiUserRespVO>({
    url: `${baseURL}/get-template-for-user`,
    data: { ...data, apiToken: await getLocalApiToken() }
  })
